package shopping.web;

import shopping.bean.Goods;
import shopping.bean.Page;
import shopping.service.GoodsService;
import shopping.service.impl.GoodsServiceImpl;
import shopping.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class GoodsServlet extends BaseServlet {
    private GoodsService goodsService = new GoodsServiceImpl();

    /**
     * 处理分页功能
     * @param req
     * @param resp
     */
    protected void page(HttpServletRequest req, HttpServletResponse resp){
//        System.out.println("经过了前台的GoodsServlet程序");
        //获取请求的参数---pageNo和pageSize
        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
        //保存pageNo和pageSize数据到Page对象
        Page<Goods> page = goodsService.page(pageNo,pageSize);
        System.out.println("goodsServlet");
        page.setUrl("goodsServlet?action=page");
        //保存Page对象到Request域中
        req.setAttribute("page",page);
        //请求转发到view/manager/goodsmanager.jsp页面
        try {
            req.getRequestDispatcher("/view/goods/goods.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
    /**
     * 处理分页功能
     * @param req
     * @param resp
     */
    protected void pageByPrice(HttpServletRequest req, HttpServletResponse resp){
//        System.out.println("经过了前台的GoodsServlet程序");
        //获取请求的参数---pageNo和pageSize
        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
        int min = WebUtils.parseInt(req.getParameter("min"), 0);
        int max = WebUtils.parseInt(req.getParameter("max"), Integer.MAX_VALUE);
        //保存pageNo和pageSize数据到Page对象
        Page<Goods> page = goodsService.pageByPrice(pageNo,pageSize,min,max);
        StringBuilder builder = new StringBuilder("goodsServlet?action=pageByPrice");
        //如果有最小价格，将其追加到builder中
        if(req.getParameter("min") != null){
            builder.append("&min=").append(req.getParameter("min"));
        }
        //如果有最大价格，将其追加到builder中
        if(req.getParameter("max") != null){
            builder.append("&max=").append(req.getParameter("max"));
        }
        System.out.println(builder.toString());
        page.setUrl(builder.toString());
        //保存Page对象到Request域中
        req.setAttribute("page",page);
        //请求转发到view/manager/goodsmanager.jsp页面
        try {
            req.getRequestDispatcher("/view/goods/goods.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
